package com.haitaoit.chengquan.module.center_service.activity.xuqiu_order;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.activity.xuqiu.XuqiuEvaluateActivity;
import com.haitaoit.chengquan.module.center_service.adapter.xuqiu_order.ServiceXuqiuAdapter;
import com.haitaoit.chengquan.module.center_service.model.ServiceXuqiuModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ServiceXuqiuActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pull_to_refresh_scrollview)
    PullToRefreshScrollView pullrefreshscrollview;
    @ViewInject(R.id.ser_xuqiu_line1)
    View ser_xuqiu_line1;
    @ViewInject(R.id.ser_xuqiu_line2)
    View ser_xuqiu_line2;
    @ViewInject(R.id.ser_xuqiu_line3)
    View ser_xuqiu_line3;
    @ViewInject(R.id.ser_xuqiu_line4)
    View ser_xuqiu_line4;
    @ViewInject(R.id.ser_xuqiu_line5)
    View ser_xuqiu_line5;
    @ViewInject(R.id.ser_xuqiu_all)
    TextView ser_xuqiu_all;
    @ViewInject(R.id.ser_xuqiu_offer)
    TextView ser_xuqiu_offer;
    @ViewInject(R.id.ser_xuqiu_end_offer)
    TextView ser_xuqiu_end_offer;
    @ViewInject(R.id.ser_xuqiu_already_pay)
    TextView ser_xuqiu_already_pay;
    @ViewInject(R.id.ser_xuqiu_finish)
    TextView ser_xuqiu_finish;
    @ViewInject(R.id.all_count)
    TextView all_count;
    @ViewInject(R.id.no_quotation_count)
    TextView no_quotation_count;
    @ViewInject(R.id.already_offer_count)
    TextView already_offer_count;
    @ViewInject(R.id.have_pay_count)
    TextView have_pay_count;
    @ViewInject(R.id.been_completed_count)
    TextView been_completed_count;

    private LinearLayout null_information_layout;
    private MyListView listView;
    private ScrollView mScrollView;    private EditText search_et;

    private boolean isFrist = true;
    private int page = 1;
    private String order_type = "all";

    private ServiceXuqiuAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_service_xuqiu);
        setTitle_V("需求订单");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout2, null);
        findViewById(R.id.search_LL).setVisibility(View.VISIBLE);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);
        search_et = (EditText)findViewById(R.id.search_et);
        search_et.setHint("请输入搜索内容...");
        findViewById(R.id.search_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (search_et.getText().toString().equals("")) {
                    ToastUtils.showToast("输入搜索内容！");
                } else {
                    isFrist = true;
                    page = 1;
                    httpGetmer_demand_list();
                }
            }
        });

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(true);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new ServiceXuqiuAdapter(this);
        adapter.setBackCall(backCall);
        listView.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        httpGetmer_demand_list();
        super.onResume();
    }

    @OnClick({R.id.ser_xuqiu_all, R.id.ser_xuqiu_offer, R.id.ser_xuqiu_end_offer,
            R.id.ser_xuqiu_already_pay, R.id.ser_xuqiu_finish,})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ser_xuqiu_all:// 全部
                setColor();
                ser_xuqiu_all.setTextColor(getResources().getColor(R.color.app_color));
                ser_xuqiu_line1.setVisibility(View.VISIBLE);

                order_type = "all";
                break;
            case R.id.ser_xuqiu_offer:// 已报价
                setColor();
                ser_xuqiu_offer.setTextColor(getResources().getColor(R.color.app_color));
                ser_xuqiu_line2.setVisibility(View.VISIBLE);

                order_type = "offer";
                break;
            case R.id.ser_xuqiu_end_offer:// 报价结束
                setColor();
                ser_xuqiu_end_offer.setTextColor(getResources().getColor(R.color.app_color));
                ser_xuqiu_line3.setVisibility(View.VISIBLE);

                order_type = "end_offer";
                break;
            case R.id.ser_xuqiu_already_pay:// 已支付
                setColor();
                ser_xuqiu_already_pay.setTextColor(getResources().getColor(R.color.app_color));
                ser_xuqiu_line4.setVisibility(View.VISIBLE);

                order_type = "already_pay";
                break;
            case R.id.ser_xuqiu_finish:// 已完成
                setColor();
                ser_xuqiu_finish.setTextColor(getResources().getColor(R.color.app_color));
                ser_xuqiu_line5.setVisibility(View.VISIBLE);

                order_type = "finish";
                break;
        }
        isFrist = true;
        page = 1;
        httpGetmer_demand_list();
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            Intent intent = new Intent();
            final int position = (Integer) obj[0];
            switch (which) {
                case R.id.ser_xuqiu_itemll:// 详情]
                case R.id.check_baojia:// 查看报价
                case R.id.check_eva:// 查看评价
//                case R.id.scrollview_listview:
                    intent.setClass(ServiceXuqiuActivity.this, ServiceXuqiuDetailActivity.class);
                    intent.putExtra("order_id", adapter.getList().get(position).getId());
                    startActivity(intent);
                    break;
                case R.id.service_finish:// 已服务
                    Dialog dlg = DialogUtil.showInfoDialog1(ServiceXuqiuActivity.this, "提示",
                            "您确定该服务已完成吗？", "确定", "还没有", new BackCall() {
                                public void deal(int which, Object... obj) {
                                    switch (which) {
                                        case R.id.confirm:// 确定
                                            httpGetmer_demand_complete_order(adapter.getList().get(position).getOrder_no());
                                            break;
                                    }
                                    super.deal(which);
                                }
                            });
                    dlg.setCanceledOnTouchOutside(true);
                    dlg.show();
                    break;
                case R.id.go_eva:// 评价需求商
                    intent.setClass(ServiceXuqiuActivity.this, XuqiuEvaluateActivity.class);
                    intent.putExtra("demand_id", adapter.getList().get(position).getId());
                    intent.putExtra("type", "2");
                    intent.putExtra("circleimage_uri", adapter.getList().get(position).getTitle_img());
                    startActivity(intent);
                    break;
            }
            super.deal(which, obj);
        }
    };

    // 列表
    private void httpGetmer_demand_list() {
        int status = 0;// 分类0全部1报价成功2报价失败3已支付4已完成
        if ("all".equals(order_type)) {
            status = 0;
        } else if ("offer".equals(order_type)) {
            status = 1;
        } else if ("end_offer".equals(order_type)) {
            status = 2;
        } else if ("already_pay".equals(order_type)) {
            status = 3;
        } else if ("finish".equals(order_type)) {
            status = 4;
        }

        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("status", status + ""));
        list.add(new NameValuePairSign("name", search_et.getText().toString()));list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("status", status + "");
        params.addQueryStringParameter("name", search_et.getText().toString());  params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getmer_demand_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<ServiceXuqiuModel> new_list = new ArrayList<ServiceXuqiuModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<ServiceXuqiuModel>();
                            break;
                        case 0:// 成功
                            JSONObject js = new JSONObject(Response);
                            all_count.setText(js.getString("all_count"));
                            no_quotation_count.setText(js.getString("no_quotation_count"));
                            already_offer_count.setText(js.getString("already_offer_count"));
                            have_pay_count.setText(js.getString("have_pay_count"));
                            been_completed_count.setText(js.getString("been_completed_count"));

                            if (all_count.getText().toString().equals("0")) {
                                all_count.setVisibility(View.GONE);
                            } else {
                                all_count.setVisibility(View.VISIBLE);
                            }
                            if (no_quotation_count.getText().toString().equals("0")) {
                                no_quotation_count.setVisibility(View.GONE);
                            } else {
                                no_quotation_count.setVisibility(View.VISIBLE);
                            }
                            if (already_offer_count.getText().toString().equals("0")) {
                                already_offer_count.setVisibility(View.GONE);
                            } else {
                                already_offer_count.setVisibility(View.VISIBLE);
                            }
                            if (have_pay_count.getText().toString().equals("0")) {
                                have_pay_count.setVisibility(View.GONE);
                            } else {
                                have_pay_count.setVisibility(View.VISIBLE);
                            }
                            if (been_completed_count.getText().toString().equals("0")) {
                                been_completed_count.setVisibility(View.GONE);
                            } else {
                                been_completed_count.setVisibility(View.VISIBLE);
                            }

                            new_list = gson.fromJson(js.getString("demand_list"),
                                    new TypeToken<List<ServiceXuqiuModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<ServiceXuqiuModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<ServiceXuqiuModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 需求服务完成订单
    private void httpGetmer_demand_complete_order(String order_no) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getmer_demand_complete_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            isFrist = true;
                            page = 1;
                            httpGetmer_demand_list();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    public void setColor() {
        ser_xuqiu_all.setTextColor(getResources().getColor(R.color.black_text));
        ser_xuqiu_offer.setTextColor(getResources().getColor(R.color.black_text));
        ser_xuqiu_end_offer.setTextColor(getResources().getColor(R.color.black_text));
        ser_xuqiu_already_pay.setTextColor(getResources().getColor(R.color.black_text));
        ser_xuqiu_finish.setTextColor(getResources().getColor(R.color.black_text));

        ser_xuqiu_line1.setVisibility(View.INVISIBLE);
        ser_xuqiu_line2.setVisibility(View.INVISIBLE);
        ser_xuqiu_line3.setVisibility(View.INVISIBLE);
        ser_xuqiu_line4.setVisibility(View.INVISIBLE);
        ser_xuqiu_line5.setVisibility(View.INVISIBLE);
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<ServiceXuqiuModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        httpGetmer_demand_list();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        httpGetmer_demand_list();
    }
}